package com.xinnet.mms.quartz.job;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xinnet.core.utils.ConfigUtil;
import com.xinnet.core.utils.INetUtils;
import com.xinnet.mms.allot.dao.CustomAllotDao;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.ScanningList;
import com.xinnet.mms.member.service.MemberService;
import com.xinnet.mms.utils.CustomerManage;


/**
 * 客户分配和同步会员
 * 
 * @author 颜绿水
 * @author $Author:$
 * @version $Revision:$ $Date:$
 * @since 2014-7-14
 * 
 */
@Service(value = "customAllotJob")
public class CustomAllotJob {

	private static Log log = LogFactory.getLog(CustomAllotJob.class);
	
	
	private static String trustServerAddr = ConfigUtil.getString("trustIp.server");
	
	
	private static String ipString = getTrustIpData(trustServerAddr,""); //认证IP列表
	
	/*{
		//发起post请求获得可信任的ip列表
		ipString = getTrustIpData(trustServerAddr + "/updateEmp.jsp","");
	}*/

	public static String getIpString() {
		return ipString;
	}
	
	
	/*设置可信任的ip列表*/
	public static void setIpString(String ipString) {
		CustomAllotJob.ipString = ipString;
	}



	/** 线程池 */
	// private static ExecutorService pool = Executors.newFixedThreadPool(5);

	private static final SimpleDateFormat sf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	/** 客户分配 */
	@Autowired
	private CustomAllotDao customAllotDao;

	@Autowired
	private CustomAllotService customAllotService;

	/** 会员中心 */
	@Autowired
	private MemberService memberService;

	/** 时间戳 */
	@Autowired
	private JobTimeService jobTimeService;

	/**
	 * 
	 * 功能描述：同步会员分配方法--定时扫描某一个时间段的会员进行分配
	 * 
	 * 
	 * @throws Exception
	 */
	@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
	public void sysnMemberAllot() {

		try {
			// 指定特定服务器IP来跑定时任务
			String ip = INetUtils.getLocalHostAddress();
			log.info("<当前IP：(" + ip + ")>");
			sysnMember();
		} catch (Throwable e) {
			e.printStackTrace();
			log.error("<同步会员出错-:" + e.getMessage() + ">", e);
		}
	}

	/**
	 * 
	 * 功能描述：同步会员分配方法--定时扫描某一个时间段的会员进行分配（线程池）
	 * @throws Exception 
	 * 
	 * 
	 * @throws Exception
	 */
	private void sysnMember() throws Exception {
		// 获取取得客户区间数
		int limit = Integer.parseInt(ConfigUtil.getString("LIMIT"));
		// 获取导入客户类型(全部/当前)
		int timeSet = Integer.parseInt(ConfigUtil.getString("GETTYPE"));

		if (timeSet == CustomerManage.TIMESET_ALL) {
			//log.info("<导入全部会员开始>");
			// 获取会员总记录数
			int count = memberService.getAllMemberCount();
			for (int top = 0; top <= count; top += limit) {
				List<Customer> list = memberService
						.getMemberByLimit(top, limit);
				if (list == null) {
					//log.info("<当前需要导入的老客户数为0>");
					return;
				} else {
					// 对获取的会员进行分配
					for (Customer customer : list) {
						customer.setCustomerSource("网站");
						customer.setCustomState(CustomerManage.ACCEPT_NO);
						customer.setPusherId("system");
						customer.setIsAllot(0);
						customer.setIsReDevel(0);
						customer.setAddTime(sf.format(new Date()));
						customer.setCustomerType(CustomerManage.NEW_CUSTOMER);
						// 如果区域为空 则默认设置为北京
						String areaName = customer.getAreaName();
						if (areaName == null || "".equals(areaName)) {
							customer.setRegionalId(CustomerManage.BEIJING);
							customer.setAreaName("北京市");
						}
						try {
							customAllotService.allot(customer,
									CustomerManage.NEW_CUSTOMER);
						} catch (Exception e) {
							/*log.error("<同步会员出错-会员ID:" + customer.getCusId()
									+ "," + e.getMessage() + ">", e);*/
						}
						/*log.info("<---TIME:" + customer.getAddTime()
								+ "---扫描新注册客户---ID：" + customer.getCusId()
								+ " UserName：" + customer.getCname() + ">");*/
					}
				}
			}
			//log.info("<导入全部会员END>");
		} else {
			//log.info("<导入区间会员开始>");
			// 获取时间戳 如果时间戳为空则添加一条当前时间的时间戳
			Customer jobTimeCustomer = new Customer();
			jobTimeCustomer = jobTimeService
					.getJobTime(CustomerManage.SYSNMEMBER);
			if (jobTimeCustomer == null) {
				jobTimeCustomer = new Customer();
				String time = sf.format(new Date());
				jobTimeCustomer.setTimeStamp(time);
				jobTimeCustomer.setJobId(UUID.randomUUID().toString());
				jobTimeCustomer.setJobType(CustomerManage.SYSNMEMBER);
				jobTimeService.addJobTime(jobTimeCustomer);
			}
			// 获取设置的时间区间的所有新注册会员
//			List<Customer> customerList = memberService
//					.getMemberByTimeSet(jobTimeCustomer.getTimeStamp());
			//为了满足会员前台修改错误分公司 改为延迟一分钟取客户
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(sf.parse(jobTimeCustomer.getTimeStamp()));
			//calendar.add(Calendar.MINUTE, -1);
			String resultTime = sf.format(calendar.getTime());
			List<Customer> customerList = memberService.getMemberByTimeSet(resultTime);
			if (customerList == null || customerList.isEmpty()) {
				log.info("<没有新注册客户>");
				return;
			}
			int count = 0;
			// 对获取的会员进行分配
			for (Customer customer : customerList) {
				/*log.info("<---TIME:" + customer.getAddTime()
						+ "---扫描新注册客户---ID：" + customer.getCusId()
						+ " UserName：" + customer.getCname() + " 当前第 【" + count
						+ "】 条|处理开始>");*/
				//如果重复则不处理,记录该会员号的时间
				if(customAllotService.getCustomerById(customer.getCusId())!=null) {
					jobTimeCustomer.setTimeStamp(customer.getAddTime());
					log.error("该会员已在crm系统中存在，会员号： "+customer.getCusId());
					continue;
				}
				
				//如会员是通过返利注册的会员，会员应按返利规则做暂停分配处理。
				if(customer.getRegisteredChannel() != null && customer.getRegisteredChannel().equals("rebate")){
					customer.setCustomerSource("网站");
					customer.setCustomState(CustomerManage.ACCEPT_NO);
					customer.setPusherId("system");
					customer.setIsAllot(CustomerManage.ALLOT_NO_RETAIN);
					customer.setIsReDevel(0);
					customer.setCustomerType(CustomerManage.NEW_CUSTOMER);
					customAllotService.addNewCustomer(customer);
					jobTimeCustomer.setTimeStamp(customer.getAddTime());
					continue;
				}
				//如果会员是通过一起发注册的过滤掉
				if(customer.getRegisterType() != null && "3".equals(customer.getRegisterType())){
					
					jobTimeCustomer.setTimeStamp(customer.getAddTime());
					continue;
				}
				
				//如果会员是邮局试用注册  
				if(customer.getRegisterType() != null && "4".equals(customer.getRegisterType())){
					
					jobTimeCustomer.setTimeStamp(customer.getAddTime());
					continue;
				}
				
				customer.setCustomerSource("网站");
				customer.setCustomState(CustomerManage.ACCEPT_NO);
				customer.setPusherId("system");
				customer.setIsAllot(0);
				customer.setIsReDevel(0);
				customer.setCustomerType(CustomerManage.NEW_CUSTOMER);
				jobTimeCustomer.setTimeStamp(customer.getAddTime());
				// 如果区域为空 则默认设置为北京
				String areaName = customer.getAreaName();
				if (areaName == null || "".equals(areaName)) {
					customer.setRegionalId(CustomerManage.BEIJING);
					customer.setAreaName("北京市");
				}
				if(areaName!=null && areaName.equals("北京")){
					customer.setRegionalId(CustomerManage.BEIJING);
					customer.setAreaName("北京市");
				}
				
				try {
					log.info("开始处理会员："+customer.getCusId());
					customAllotService.allot(customer,
							CustomerManage.NEW_CUSTOMER);
					log.info("处理会员结束："+customer.getCusId());
				} catch (Exception e) {
					jobTimeService.updateJobTime(jobTimeCustomer);
					log.error(
							"<同步区间会员出错-会员ID:" + customer.getCusId() + ","
									+ e.getMessage() + " 任务停止>", e);
					return;
				}
				count++;
				/*log.info("<---TIME:" + customer.getAddTime()
						+ "---扫描新注册客户---ID：" + customer.getCusId()
						+ " UserName：" + customer.getCname() + " 当前第 【" + count
						+ "】 条|处理完毕>");*/
			}
			log.info("开始更新记录时间："+jobTimeCustomer.getTimeStamp());
			jobTimeService.updateJobTime(jobTimeCustomer);
			log.info("更新记录时间成功："+jobTimeCustomer.getTimeStamp());
			//log.info("<导入区间会员END>");
		}
	}

	/**
	 * 功能描述： quartz定式扫描timeList方法
	 * 
	 * @throws Exception
	 */
	public void scanningTimeList() throws Exception {
		// 指定特定服务器IP来跑定时任务
		String ip = INetUtils.getLocalHostAddress();
		log.info("<当前IP：(" + ip + ")>");
		// if(ConfigUtil.getString("web2.server").equals(ip)){

		// pool.execute(new Runnable() {
		// @Override
		// public void run() {
		try {
			scanningTimeListByThreadPool();
		} catch (Exception e) {
			log.error("<超时重新分配会员出错-:" + e.getMessage() + ">", e);
		}
		// }
		// });
		// }
	}

	/**
	 * 功能描述： quartz定式扫描timeList方法(线程池)
	 * 
	 * @throws Exception
	 */
	private void scanningTimeListByThreadPool() throws Exception {
		log.info("<超时扫描开始>");
		List<ScanningList> list = customAllotDao.getAllScanningList();
		// 时间列表中有客户数据时进行处理
		if (list == null || list.isEmpty()) {
			log.info("<当前没有客户需要超时分配>");
			return;
		}
		//1.获取所有员工id。存入 分公司-部门 对象
		//2.每次传入对象，设置flag位，下次轮循继续执行

		//log.info("<扫描业务员接收客户状态" + "当前待接收客户个数:(" + list.size() + ")>");

		int count = 0;
		for (ScanningList scann : list) {
			count++;
			//log.info("超时扫描处理第【" + count + "】条开始");
			customAllotService.handleScaningList(scann);
			//log.info("超时扫描处理第【" + count + "】条结束");
		}
	}
	
	
	
	
	
	/**
	 * 功能描述： quartz定时同步信任IP列表
	 * 
	 * @throws Exception
	 */
	@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
	public void syncTrustIp() throws Exception {
//		ipString = getTrustIpData(trustServerAddr,"");
		
		String ipResult = getTrustIpData(trustServerAddr,"");
		/*log.info("定时调用信任IP列表接口返回值："+ipResult);*/
		if(StringUtils.isNotBlank(ipResult)){
			ipString = ipResult;
		}
		
	}
	
	
	/**
	 * 获取信任IP列表
	 * @param hostUrl 请求URL
	 * @param body 请求内容
	 * @return
	 */
	public static String getTrustIpData(String hostUrl, String body){
		
		/*if(1==1){
			return "10.12.34.56";
		}*/
		log.info("请求地址为："+hostUrl);
		log.info("请求开始时间========>"+System.currentTimeMillis());
		URL url = null;
		OutputStream output = null;
		OutputStreamWriter outr = null;
		StringBuffer buffer = new StringBuffer();
		InputStream inputStream = null;
		BufferedReader inReader = null;

		try {
			url = new URL(hostUrl);
			HttpURLConnection httpurlconnection = (HttpURLConnection) url.openConnection();
			HttpURLConnection.setFollowRedirects(true);
			httpurlconnection.setDoOutput(true);
			httpurlconnection.setConnectTimeout(30000);
			httpurlconnection.setReadTimeout(120000);
			httpurlconnection.setRequestMethod("POST");
			httpurlconnection.connect();
			
			output = httpurlconnection.getOutputStream();
			outr = new OutputStreamWriter(output,"utf-8");
			
			outr.write(body.toCharArray(), 0, body.length());
			
			outr.flush();
			outr.close();
			
			int code = httpurlconnection.getResponseCode();
			if (code == 200){
				
				inputStream = httpurlconnection.getInputStream();
				inReader = new BufferedReader(new InputStreamReader(inputStream));
	              
	            String line = "";
	            while ((line = inReader.readLine()) != null){
	                buffer.append(line);
	            }
	            inReader.close();
			}else{
				log.error("非正常调用IP认证接口返回httpcode: "+code);
			}
			
			httpurlconnection.disconnect();
			
		}catch (Exception e) {
			log.error("连接报错："+e.getMessage(), e);
		}
		log.info("请求结束时间========>"+System.currentTimeMillis());
		return buffer.toString();
	}
	
	/**
	 * 功能描述： 将未接收客户重新分配销售
	 * addtime：2016年10月25日14:44:17
	 */
	public void reallocateCustom(){
		
	}
	
	public static void main(String[] args) {
		
		/*
		String result = getTrustIpData("http://agent.xinnet.com/updateEmp.jsp", "");
		String clientIP = "124.127.244.1";
//		String clientIP = INetUtils.getLocalHostAddress();
		log.info("客户端公网IP地址："+clientIP);
		String[] resultArray = result.replace("[", "").replace("]", "").split(",");
		
		//是否通过验证的标识,
		//false:未通过
		//true:通过
		boolean flag = false;
		
		//初始化加密类
		MessageDigestPasswordEncoder mdpeSha = new MessageDigestPasswordEncoder("SHA-256");  
		mdpeSha.setEncodeHashAsBase64(false);  
		//生成加密后的IP地址
		String shaPassword = mdpeSha.encodePassword(clientIP, null);
		log.info("加密后的客户端公网IP地址："+shaPassword);
	    for(int i=0;i<resultArray.length;i++){
	    	if(shaPassword.trim().equals(resultArray[i].trim())){
	    		flag = true;
	    		break;
	    	}
		}
	    if(flag){
	    	log.info(">>>>IP验证通过,在信任列表中");
	    }else{
	    	log.info("<<<<<>>>>IP验证不通过,不在信任列表中");
    	}
		System.err.println(getTrustIpData("http://agent.xinnet.com/updateEmp.jsp", ""));*/
		getTrustIpData("http://agent.xinnet.com/updateEmp.jsp", "");
		
//		String clientIP = "180.153.206.33";
//		MessageDigestPasswordEncoder mdpeSha = new MessageDigestPasswordEncoder("SHA-256");  
//		mdpeSha.setEncodeHashAsBase64(false);  
//		//生成加密后的IP地址
//		String shaPassword = mdpeSha.encodePassword(clientIP, null);
//		System.out.println(shaPassword);
	}
	
	
}
